package common.loader {

	import flash.display.Bitmap;
	import flash.events.Event;
	import flash.utils.Dictionary;
	import flash.utils.setTimeout;
	
	public class LoaderManager {
		
		private static var resourceLoader:ResourceLoader;
		private static var infoList:Array = new Array();
		private static var parseList:Array = new Array();
		private static var idle:uint = 2;
		private static const MAX:uint = 2;
		private static var resouceList:Dictionary = new Dictionary();
		private static var loadingList:Dictionary = new Dictionary();

		public function LoaderManager() {
			
		}
		
		public static function init():void {
			resourceLoader = new ResourceLoader();
			resourceLoader.handler = resourceHandler;
			BaseLoader.init(MAX);
		}
		
		public static function add(url:String, type:uint = LoaderType.BINARY, handler:Function = null):void {
			if (resouceList[url] != null) {
				if (handler != null) {
					handler(resouceList[url]);
				}
			} else {
				if (loadingList[url] != null) {
					loadingList[url].push(handler);
					return;
				} else {
					loadingList[url] = [handler];
				}
				var info:Info = new Info();
				info.url = url;
				info.type = type;
//				info.handler = handler;
				infoList.push(info);
				load();
			}
		}
		
		public static function load():void {
			if (infoList.length > 0 && idle > 0) {
				BaseLoader.add(infoList.shift() as Info, loaderHandler);
				idle--;
			}
		}
		
		private static function loaderHandler(info:Info):void {
			idle++;
			var handler:Function;
			if (info.type == LoaderType.MESSAGE || info.type == LoaderType.TEXT) {
				var str:String = info.raw.toString();
				for each (handler in loadingList[info.url]) {
					handler(str);
				}
				delete loadingList[info.url];
			} else if (info.type == LoaderType.IMAGE || info.type == LoaderType.SWF) {
				if (resourceLoader.finish) {
					parse(info);
				} else {
					parseList.push(info);
				}
			}
			load();
		}
		
		private static function parse(info:Info):void {
			resourceLoader.start(info);
		}
		
		private static function resourceHandler(info:Info):void {
			var handler:Function;
			if (info.type == LoaderType.IMAGE) {
				for each (handler in loadingList[info.url]) {
					handler((info.data as Bitmap).bitmapData);
				}
//				if (info.handler != null) {
//					info.handler((info.data as Bitmap).bitmapData);
//				}
			} else if (info.type == LoaderType.SWF) {
				for each (handler in loadingList[info.url]) {
					handler(info);
				}
//				if (info.handler != null) {
//					info.handler(info);
//				}
			}
			delete loadingList[info.url];
			if (parseList.length > 0) {
				parse(parseList.shift() as Info);
			}
		}
	}
}